import { getProductList, addProduct, updateProduct, deleteProduct, getProductCategories } from '@/api/products'

const state = {
  list: [],
  total: 0,
  loading: false,
  categories: []
}

const mutations = {
  SET_LIST: (state, list) => {
    state.list = list
  },
  SET_TOTAL: (state, total) => {
    state.total = total
  },
  SET_LOADING: (state, loading) => {
    state.loading = loading
  },
  SET_CATEGORIES: (state, categories) => {
    state.categories = categories
  }
}

const actions = {
  // Get product list
  getProductList({ commit }, params) {
    commit('SET_LOADING', true)
    return new Promise((resolve, reject) => {
      getProductList(params)
        .then(response => {
          const { data } = response
          commit('SET_LIST', data.items)
          commit('SET_TOTAL', data.total)
          commit('SET_LOADING', false)
          resolve(data)
        })
        .catch(error => {
          commit('SET_LOADING', false)
          reject(error)
        })
    })
  },

  // Get product categories
  getProductCategories({ commit }) {
    return new Promise((resolve, reject) => {
      getProductCategories()
        .then(response => {
          const { data } = response
          commit('SET_CATEGORIES', data)
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // Add product
  addProduct(_, productData) {
    return new Promise((resolve, reject) => {
      addProduct(productData)
        .then(response => {
          const { data } = response
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // Update product
  updateProduct(_, { id, data }) {
    return new Promise((resolve, reject) => {
      updateProduct(id, data)
        .then(response => {
          const { data } = response
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // Delete product
  deleteProduct(_, id) {
    return new Promise((resolve, reject) => {
      deleteProduct(id)
        .then(response => {
          const { data } = response
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 